package com.yc.io.pdf;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

import com.UpYun;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

/**
 * author: yc
 * description: 根据pdf模板生成pdf文件
 * date: 2021/11/1 15:39
 */
public class ChangePdf3 {
    // 模板路径
//    static String PDF_TEMPLATE_PATH = "D:\\source\\word\\项目\\other\\template.pdf";
    static String PDF_TEMPLATE_PATH = "https://cdd-static-upy.chediandian.com/front/exchangegoods/goods/38f74b944df241a680de088e853fba7b.pdf";

    // 利用模板生成pdf
    public static void pdfout(Map<String,Object> o) {
        // 生成的新文件路径
        String newPDFPath = "D:\\source\\word\\项目\\中华保险\\out_" + System.currentTimeMillis() + ".pdf";

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(PDF_TEMPLATE_PATH);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            //文字类的内容处理
            Map<String,String> datemap = (Map<String,String>)o.get("datemap");
            form.addSubstitutionFont(bf);
            for(String key : datemap.keySet()){
                String value = datemap.get(key);
                form.setField(key,value);
            }
            //图片类的内容处理
            Map<String,String> imgmap = (Map<String,String>)o.get("imgmap");
            for(String key : imgmap.keySet()) {
                String value = imgmap.get(key);
                String imgpath = value;
                int pageNo = form.getFieldPositions(key).get(0).page;
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();
                //根据路径读取图片
                Image image = Image.getInstance(imgpath);
                //获取图片页面
                PdfContentByte under = stamper.getOverContent(pageNo);
                //图片大小自适应
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                //添加图片
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }
            stamper.setFormFlattening(true);// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

//            PdfImportedPage importPage1 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
//            copy.addPage(importPage1);//第1页
            PdfImportedPage importPage2 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 2);
            copy.addPage(importPage2);//第2页

            doc.close();

        } catch (IOException e) {
            System.out.println(e);
        } catch (DocumentException e) {
            System.out.println(e);
        }

    }

    //往又拍云传文件
    public void uploadImg() {
        try {
            File file = new File(PDF_TEMPLATE_PATH);
            Long len = file.length();
            FileInputStream fi = new FileInputStream(file);
            byte[] bytes = new byte[len.intValue()];
            fi.read(bytes);
//            Reader reader = new FileReader(new File(PDF_TEMPLATE_PATH));

//            byte[] bytes = file.getBytes();
            String UpYunFilePath = "/front/exchangegoods/goods/" + getGuid(true) + ".pdf";
            String UpYunUrlPath = "https://cdd-static-upy.chediandian.com";
            UpYun upyun = new UpYun("cdd-static", "cddupload", "7p8o0ef953fz");
            boolean result = upyun.writeFile(UpYunFilePath, bytes, true);
            if (result) {
                System.out.println("上传成功:" + UpYunUrlPath + UpYunFilePath);
            } else {
                System.out.println("上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getGuid(boolean isRemoveHyphen) {
        String str = java.util.UUID.randomUUID().toString();
        return isRemoveHyphen ? str.replace("-", "") : str;
    }

    public void m2() {
        String folder=System.getProperty("java.io.tmpdir");
        System.out.println(folder);
    }



    public static void main(String[] args) {
        Map<String,String> map = new HashMap();
        map.put("userName", "张三");
        map.put("carPlate", "浙B12345");
        map.put("date", "2021-09-09");

        Map<String,String> map2 = new HashMap();
//        map2.put("sign1_af_image","https://cdd-static-upy.chediandian.com/actives_2021/10/cicpStaic/img/sign.png");
        map2.put("sign2_af_image","https://cdd-static-upy.chediandian.com/actives_2021/10/cicpStaic/img/sign.png");

        Map<String,Object> o=new HashMap();
        o.put("datemap",map);
        o.put("imgmap",map2);
        pdfout(o);

//        ChangePdf3 cp = new ChangePdf3();
//        cp.uploadImg();
//        cp.m2();
    }
}
